package org.halk.job_client.component;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.halk.job_client.annotion.BiJobMapping;
import org.halk.job_client.mq.produce.JobProduce;
import org.halk.job_client.pojo.entity.JobRequest;
import org.halk.job_client.pojo.entity.JobResponse;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.HashMap;

@Slf4j
public class JobContext {

    /**
     * 用于存放任务id和对应得bean
     */
    private static final HashMap<String, Object> idToBeanMap = new HashMap<>();

    @Setter
    private static String server;

    @Setter
    private static JobProduce JobProduce;

    public static void putJobClass(String jobId, Object bean) {
        idToBeanMap.put(jobId, bean);
    }

    public static void run(JobRequest request) {
        if (!request.getServer().equals(server)) {
            //不是本机任务，直接返回
            return;
        }
        if (!idToBeanMap.containsKey(request.getScheduleId())) {
            //是否已经注册过该任务
            return;
        }
        Object bean = idToBeanMap.get(request.getScheduleId());
        for (Method method : bean.getClass().getMethods()) {
            if (!method.isAnnotationPresent(BiJobMapping.class)) {
                //不包含这个注解得方法跳过
                continue;
            }
            BiJobMapping annotation = method.getAnnotation(BiJobMapping.class);
            String value = annotation.value();
            if (request.getScheduleId().equals(value)) {
                //执行完后发送结果
                JobResponse jobResponse = new JobResponse()
                        .setMsgId(request.getMsgId())
                        .setScheduleId(request.getScheduleId());
                //执行该方法
                try {
                    method.invoke(bean);
                    jobResponse.setStatus(1);
                } catch (InvocationTargetException e) {
                    // 获取原始异常
                    Throwable cause = e.getCause();
                    log.info("执行任务失败, 方法:{}, 参数:{}, 异常: {}，{}", method.getName(), bean, cause.getClass().getName(), cause.getMessage());
                    jobResponse.setStatus(2); // 执行失败，设置状态为2
                    jobResponse.setError(getFullErrorMessage(cause)); // 设置错误信息
                } catch (Exception e) {
                    log.info("执行任务失败, 方法:{}, 参数:{}, 异常: {},{}", method.getName(), bean.getClass().getName(), e.getMessage());
                    jobResponse.setStatus(2); // 执行失败，设置状态为2
                    jobResponse.setError(getFullErrorMessage(e)); // 设置错误信息
                } finally {
                    jobResponse.setEndTime(LocalDateTime.now());
                    JobProduce.sendJobMsg(jobResponse);
                }

            }

        }
    }

    private static String getFullErrorMessage(Throwable e) {
        String className = e.getClass().getName();
        String message = e.getMessage();
        String fullErrorMessage = message != null ? className + ": " + message : className;
        return fullErrorMessage.substring(0, Math.min(fullErrorMessage.length(), 500));
    }

}
